package com.gang.mars.redisson.Thread;

import lombok.SneakyThrows;

public class Apple14ProduceAndConsume {

    public static void main(String[] args) {
        new Apple14ProduceAndConsume().test();
    }

    private void test(){
        SynContainer synContainer = new SynContainer();

        new Produce(synContainer).start();
        new Consumer(synContainer).start();
    }


    class Produce extends Thread{

        SynContainer container;

        public Produce(SynContainer container) {
            this.container = container;
        }


        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                container.push(new Chicken(i));
                System.out.println("生产第 " + i +" 鸡");
            }
        }
    }

    class Consumer extends Thread{

        SynContainer container;

        public Consumer(SynContainer container) {
            this.container = container;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("消费第 " + container.pop().id + " 只鸡");
            }
        }
    }

    class Chicken{
        private int id;

        public Chicken(int id) {
            this.id = id;
        }
    }

    class SynContainer{

        int count = 0;

        Chicken[] chickens = new Chicken[10];

        @SneakyThrows
        public synchronized void push(Chicken chicken){

            if (count == chickens.length) {
                this.wait();
            }else {
                chickens[count] = chicken;
                count++;
                this.notifyAll();
            }
        }


        @SneakyThrows
        public  synchronized Chicken pop(){

            if (count == 0) {
                this.wait();
            }
            count --;
            Chicken chicken = chickens[count];

            this.notifyAll();

            return chicken;

        }


    }
}
